<script setup>
import { ref, onMounted } from 'vue'
import { queryAllApi as queryClazzList } from '@/api/clazz'
import { queryPageApi, addApi, queryInfoApi, updateApi, deleteApi, violationApi } from '@/api/stu'
import { ElMessage, ElMessageBox } from 'element-plus'


//搜索表单元数据
const searchStu = ref({
  name: '',
  degree: '',
  clazzId: '',
})
//学历列表
const degreeList = ref([
  { name: '初中', value: '1' },
  { name: '高中', value: '2' },
  { name: '大专', value: '3' },
  { name: '本科', value: '4' },
  { name: '硕士', value: '5' },
  { name: '博士', value: '6' },
  { name: '其他', value: '7' },
])
//性别列表
const genderList = ref([
  { name: '男', value: 1 },
  { name: '女', value: 2 },
])
//班级列表
const clazzList = ref([])
//获取所有班级列表
const queryAllClazz = async () => {
  const result = await queryClazzList();
  if (result.code) {
    clazzList.value = result.data
  }
}

//钩子函数
onMounted(async () => {
  //查询班级列表
  queryAllClazz();
  search();
})

//学员列表
const stuList = ref([])

//查询
const search = async () => { 
  const result = await queryPageApi(
    searchStu.value.name,
    searchStu.value.degree,
    searchStu.value.clazzId,
    page.value,
    pageSize.value
  )
  if (result.code) { 
    stuList.value = result.data.rows;
    total.value = result.data.total;
  }
}

//分页查询参数
const page = ref(1)
const pageSize = ref(10)
const total = ref(100)
//更改页码触发
const handleCurrentChange = (val) => {
  page.value = val;
  search();
}
//改变每页记录数触发
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
}

//清空查询条件
const clear = () => { 
  searchStu.value = {
    name: '',
    degree: '',
    clazzId: '',
  }
  search();
}

//新增/修改学员
const stu = ref({
    "name": "",
    "no": "",
    "gender": "",
    "phone": "",
    "idCard": "",
    "isCollege": "",
    "address": "",
    "degree": "",
    "graduationDate": "",
    "clazzId": ""
})
const dialogStuVisible = ref(false)
const dialogStuTitle = ref('')
//新增
const add = () => { 
  stu.value = {
    "name": "",
    "no": "",
    "gender": "",
    "phone": "",
    "idCard": "",
    "isCollege": "",
    "address": "",
    "degree": "",
    "graduationDate": "",
    "clazzId": ""
  }
  dialogStuTitle.value = '新增学员';
  dialogStuVisible.value = true;
  clearForm();
}
//修改
const edit = async (id) => { 
  dialogStuTitle.value = '修改学员';
  dialogStuVisible.value = true;
  const result = await queryInfoApi(id);
  if (result.code) { 
    stu.value = result.data;
  }
}
//表单验证
const rules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{6,10}$/, message: '长度在 6 到 10 个字符，且只能输入数字', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20|21|22|23|24|25|26|27|28|29|30|31)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9xX]$/, message: '请输入正确的身份证号'}
  ], 
  isCollege: [
    { required: true, message: '请选择是否为院校', trigger: 'change' }
  ]
}
//表单引用
const stuRuleFormRef = ref()
//重置表单校验规则
const clearForm = () => { 
  if (stuRuleFormRef.value) {
    stuRuleFormRef.value.resetFields();
  }
}
//保存学员
const save = async () => { 
  //表单校验
  if (!stuRuleFormRef.value) {
    return;
  }
  stuRuleFormRef.value.validate(async valid => { 
    if (valid) { //通过表单验证
      let result;
      if (!stu.value.id) { //添加
        result = await addApi(stu.value);
      } else { //修改
        result = await updateApi(stu.value);
      }
      if (result.code) { //成功
        dialogStuVisible.value = false;
        ElMessage.success('保存成功');
        search();
      } else {  //失败
        ElMessage.error(result.msg);
      }
    } else { //不通过表单验证
      ElMessage.error("表单校验不通过");
    }
  });
}

//删除
//复选框触发事件
const selectedIds = ref([]);
const handleSelectionChange = (ids) => {
  selectedIds.value = ids.map((item) => item.id);
};
//根据Ids批量删除学员
const deleteById = async (ids) => { 
  if (ids.length == 0) {  //检查复选框是否选中数据
    ElMessage.info('请选择要删除的员工');
    return;
  }
  //弹出确认框
  ElMessageBox.confirm('请确认是否删除所选学员, 删除操作不可撤销!','警告',
    {
      confirmButtonText: '确认删除', cancelButtonText: '取消', 
      type: 'warning',
      confirmButtonClass: 'el-button--danger', //确认按钮样式为 danger
      autofocus: false  //取消自动聚焦于确认按钮
    }
  ).then(async () => { //确认
    const result = await deleteApi(ids);
    if (result.code) {
      ElMessage.success('删除学员成功');
      search();
    } else {
      ElMessage.error(result.msg);
    }
  }).catch(() => {
    ElMessage.info('取消删除学员');
  })
}

//违纪处分操作
const dialogViolationVisible = ref(false);
const score = ref();
const violationId = ref();
const violation = (id) => { 
  dialogViolationVisible.value = true;
  violationId.value = id;
}
//违纪处分提交
const violationSubmit = async () => { 
  ElMessageBox.confirm('请确认是否提交违纪处分, 该操作不可撤销', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => { //确认
    const result = await violationApi(violationId.value, score.value);
    if (result.code) { 
      ElMessage.success('违纪扣分操作成功');
      dialogViolationVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg);
    }
  })
}
</script>

<template>
  <h1>学员管理</h1>
  <!-- 搜索表单 -->
  <div class="container">
    <el-form :inline="true" :model="searchStu">
      <el-form-item label="姓名" style="width: 300">
        <el-input v-model="searchStu.name" placeholder="请输入员工姓名" clearable />
      </el-form-item>

      <el-form-item label="最高学历" style="width: 300">
        <el-select v-model="searchStu.degree" placeholder="请选择">
          <el-option v-for="d in degreeList" :key="d.value" :label="d.name" :value="d.value" />
        </el-select>
      </el-form-item>
       <el-form-item label="所属班级" style="width: 300">
        <el-select v-model="searchStu.clazzId" placeholder="请选择">
          <el-option v-for="c in clazzList" :key="c.id" :label="c.name" :value="c.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 功能按钮 -->
  <div class="container">
    <el-button type="success" @click="add">+ 新增学员</el-button>
    <el-button type="danger" @click="deleteById(selectedIds)">- 批量删除</el-button>
  </div>

  <!-- 表格内容 -->
  <el-table :data="stuList" border style="width: fit-content" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50" align="center" />
    <el-table-column prop="name" label="名字" width="100" align="center" />
    <el-table-column prop="no" label="学号" width="150" align="center" />
    <el-table-column prop="clazzName" label="班级" width="180" align="center" />
    <el-table-column prop="gender" label="性别" width="80" align="center">
      <template #default="scope">
        <el-text v-if="scope.row.gender == 1">男</el-text>
        <el-text v-else>女</el-text>
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="160" align="center" />
    <el-table-column prop="degree" label="最高学历" width="100" align="center">
      <template #default="scope">
        <el-text v-if="scope.row.degree == 1">{{ degreeList[0].name }}</el-text>
        <el-text v-else-if="scope.row.degree == 2">{{ degreeList[1].name }}</el-text>
        <el-text v-else-if="scope.row.degree == 3">{{ degreeList[2].name }}</el-text>
        <el-text v-else-if="scope.row.degree == 4">{{ degreeList[3].name }}</el-text>
        <el-text v-else-if="scope.row.degree == 5">{{ degreeList[4].name }}</el-text>
        <el-text v-else-if="scope.row.degree == 6">{{ degreeList[5].name }}</el-text>
        <el-text v-else>{{ degreeList[6].name }}</el-text>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="100" align="center" />
    <el-table-column prop="violationScore" label="违纪扣分" width="100" align="center" />
    <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" />
    <el-table-column label="操作" width="300" align="center" >
      <template #default="scope">
        <el-button type="primary" @click="edit(scope.row.id)" size="small"><el-icon><Edit /></el-icon>编辑</el-button>
        <el-button type="warning" @click="violation(scope.row.id)" size="small"><el-icon><WarningFilled /></el-icon>违纪</el-button>
        <el-button type="danger" @click="deleteById(scope.row.id)" size="small"><el-icon><Delete /></el-icon>删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页条 -->
  <div class="container">
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 50, 75, 100]"
      background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增/修改学员对话框 -->
  <el-dialog v-model="dialogStuVisible" :title="dialogStuTitle" width="1270">
    <el-form ref="stuRuleFormRef" style="max-width: 1200" :model="stu" :rules="rules" label-width="80px">
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="stu.name" placeholder="请输入学员姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="stu.no" placeholder="请输入学员学号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    
      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="stu.gender" placeholder="请选择" style="width: 100%">
              <el-option v-for="g in genderList" :key="g.value" :label="g.name" :value="g.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone" >
            <el-input v-model="stu.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard" >
            <el-input v-model="stu.idCard" placeholder="请输入身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校" prop="isCollege">
            <el-select v-model="stu.isCollege" placeholder="请选择" style="width: 100%">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址" >
            <el-input v-model="stu.address" placeholder="请输入联系地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历" >
            <el-select v-model="stu.degree" placeholder="请选择" style="width: 100%">
              <el-option v-for="d in degreeList" :key="d.value" :label="d.name" :value="d.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间" >
            <el-date-picker v-model="stu.graduationDate" type="date" placeholder="请选择毕业时间" style="width: 100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" >
            <el-select v-model="stu.clazzId" placeholder="请选择" style="width: 100%">
              <el-option v-for="c in clazzList" :key="c.id" :label="c.name" :value="c.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogStuVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 违纪处分对话框 -->
  <el-dialog v-model="dialogViolationVisible" title="违纪处理" width="500">
    <span>请输入违纪扣分</span>
    <el-input v-model="score"/>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogViolationVisible = false">取消</el-button>
        <el-button type="primary" @click="violationSubmit">确认</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
.container {
  margin: 10px 0;
}
</style>